package com.UI;

/**
 * @author Anshul
 * */

/**This file for creating user preferences. 
 **/

import com.Model.StudentDBModel;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.os.Bundle;
import android.preference.*;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.util.Log;

/*
 * The purpose of this class to have a settings tab so that the user can anytime change his defined settings:
 * For example changing the major, university, how he wants his courses shown etc. 
 */

public class Preferences extends PreferenceActivity {
	final StudentDBModel model = new StudentDBModel(this);

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setPreferenceScreen(createPreferenceHeirarchy(model));
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	// private ContentValues preferencekeyvaluePair;

	private PreferenceScreen createPreferenceHeirarchy(
			final StudentDBModel model) {
		model.addPreferences();// setting the default preferences
		ContentValues userDetails = model.getUserDetails();

		String webmailinfo = model.getWebmailUrl();

		final ContentValues prefChoices = model.getPreferences();

		OnPreferenceChangeListener pref1 = new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference userdetailspref,
					Object name) {
				// if its webmail preference then deal with it.
				ContentValues values;
				if (userdetailspref.getKey().equals("Webmail")) {
					values = new ContentValues();
					values.put("WebmailAddress", name.toString());
	        		if(name.toString().length() == 0) {
	            	      
	          		   AlertDialog alertDialog = new AlertDialog.Builder(Preferences.this).create();	        			
	          		   alertDialog.setTitle("Warning");	        		  
	          		   alertDialog.setMessage("You cannot leave it blank. Changes are not saved");	        		  	        		  
	          		   alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
	          		  
	          		   public void onClick(DialogInterface dialog, int which) {
	          			   setPreferenceScreen(createPreferenceHeirarchy(model));
	         		       return;
	         		  } }); 
	         		  alertDialog.show();
	         		  
	         		}
	        		
	        		else {
					model.updateWebmail(values);
					userdetailspref.setSummary(name.toString());

					model.updateWebmail(values);
	        		}
				}
				// if its user preference then deal with it
				else {
					values = new ContentValues();
					values.put(userdetailspref.getKey(), name.toString());
					userdetailspref.setSummary(name.toString());
	        		if(name.toString().length() == 0) {
	            	      
		          		   AlertDialog alertDialog = new AlertDialog.Builder(Preferences.this).create();	        			
		          		   alertDialog.setTitle("Warning");	        		  
		          		   alertDialog.setMessage("You cannot leave it blank. Changes are not saved");	        		  	        		  
		          		   alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
		          		  
		          		   public void onClick(DialogInterface dialog, int which) {
		          			   setPreferenceScreen(createPreferenceHeirarchy(model));
		         		       return;
		         		  } }); 
		         		  alertDialog.show();
		         		  
		         		}
		        		
		        		else {
		        			model.updateUser(values);
		        		}
				}
				return true;

			}
		};
		final AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
		/*
		 * when the checkbox in the preference is checked or unchecked the
		 * following listener is invoked
		 */
		OnPreferenceChangeListener checkboxListener = new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference pref, Object choice) {

				CheckBoxPreference checkpref = (CheckBoxPreference) pref;
				String prefKey = checkpref.getKey().toString();
				if (prefKey.equals("trackgrades")) {

					if (checkpref.isChecked()) {
						prefChoices.remove("trackgrades");
						prefChoices.put("trackgrades", "YES");
					}

					else if (!checkpref.isChecked()) {
						prefChoices.remove("trackgrades");
						prefChoices.put("trackgrades", "NO");
					}
				} else if (prefKey.equals("startapp")) {

					if (checkpref.isChecked()) {
						prefChoices.remove("startapp");
						prefChoices.put("startapp", "YES");
					}

					else if (!checkpref.isChecked()) {
						prefChoices.remove("startapp");
						prefChoices.put("startapp", "NO");
					}
				}
				model.updatePreferences(prefChoices);

				return true;
			}
		};
		/** This takes care of the onclick for deletingcourses */
		OnPreferenceClickListener pref2 = new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				// TODO Auto-generated method stub

				if (preference.getKey().equals("deletecourses")) {
					model.deleteAllCourses();
					preference
							.setSummary("You have no courses saved in the Student Notebook");
				}

				return false;
			}
		};

		OnPreferenceChangeListener putonSilentListener = new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference pref, Object choice) {
				CheckBoxPreference silentCheckpref = (CheckBoxPreference) pref;
				if(!silentCheckpref.isChecked()){
					manager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
				}
				else{
					manager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
				}
					
					
				return true;
			}
		};
		
		PreferenceScreen root = getPreferenceManager().createPreferenceScreen(
				this);

		PreferenceCategory dialogBasedPrefCat = new PreferenceCategory(this);
		dialogBasedPrefCat.setTitle("Preferences");
		root.addPreference(dialogBasedPrefCat);

		// checkbox for opening course on once the app is started

		CheckBoxPreference startapp = new CheckBoxPreference(this);
		startapp.setKey("startapp");
		startapp.setTitle("Start up app with course");
		startapp.setSummary("On start up launches the course that "
				+ "you are in according to the time specified");
		if (prefChoices.getAsString("startapp").equals("YES")) {
			startapp.setChecked(true);
		} else {
			startapp.setChecked(false);
		}
		startapp.setOnPreferenceChangeListener(checkboxListener);
		dialogBasedPrefCat.addPreference(startapp);

		// checkbox for tracking grades

		CheckBoxPreference trackGrades = new CheckBoxPreference(this);
		trackGrades.setKey("trackgrades");
		trackGrades.setTitle("Track Grades");
		trackGrades.setSummary("Keep a track of grades in tests/"
				+ "assignments/projects etc. throughout the course");
		if (prefChoices.getAsString("trackgrades").equals("YES")) {
			trackGrades.setChecked(true);
		} else {
			trackGrades.setChecked(false);
		}
		trackGrades.setOnPreferenceChangeListener(checkboxListener);
		dialogBasedPrefCat.addPreference(trackGrades);

		// adding preferences to dialog
		// first name
		EditTextPreference firstNamepref = new EditTextPreference(this);
		firstNamepref.setDialogTitle("Change your First Name");
		firstNamepref.setKey("FirstName");
		firstNamepref.setTitle("First Name");
		firstNamepref.setSummary(userDetails.getAsString("FirstName"));
		// commiting the changes made if any to the database
		firstNamepref.setOnPreferenceChangeListener(pref1);
		dialogBasedPrefCat.addPreference(firstNamepref);

		// last name

		EditTextPreference lastNamepref = new EditTextPreference(this);
		lastNamepref.setDialogTitle("Change your Last Name");
		lastNamepref.setKey("LastName");
		lastNamepref.setTitle("Last Name");
		lastNamepref.setSummary(userDetails.getAsString("LastName"));
		// commiting the changes made if any to the database
		lastNamepref.setOnPreferenceChangeListener(pref1);
		dialogBasedPrefCat.addPreference(lastNamepref);

		// Major

		EditTextPreference majorPref = new EditTextPreference(this);
		majorPref.setDialogTitle("Change your major");
		majorPref.setKey("Major");
		majorPref.setTitle("Major");
		majorPref.setSummary(userDetails.getAsString("Major"));
		// commiting the changes made if any to the database
		majorPref.setOnPreferenceChangeListener(pref1);
		dialogBasedPrefCat.addPreference(majorPref);

		// University

		EditTextPreference universityPref = new EditTextPreference(this);
		universityPref.setDialogTitle("Change your University");
		universityPref.setKey("University");
		universityPref.setTitle("University");
		universityPref.setSummary(userDetails.getAsString("University"));
		// commiting the changes made if any to the database
		universityPref.setOnPreferenceChangeListener(pref1);
		dialogBasedPrefCat.addPreference(universityPref);

		EditTextPreference webmailPref = new EditTextPreference(this);
		webmailPref.setDialogTitle("Change your Webmail");
		webmailPref.setKey("Webmail");
		webmailPref.setTitle("Webmail");
		webmailPref.setSummary(webmailinfo);
		// commiting the changes made if any to the database
		webmailPref.setOnPreferenceChangeListener(pref1);
		dialogBasedPrefCat.addPreference(webmailPref);

		// delete all courses

		Preference deletecourses = new Preference(this);
		deletecourses.setKey("deletecourses");
		deletecourses.setTitle("Delete all courses");
		// if no courses then dont do anything with the button. no onclick
		// listener to be defined when no courses present
		if (model.getNumCourses() > 0) {
			deletecourses
					.setSummary("Deletes all courses so far in your Student Notebook");
			deletecourses.setOnPreferenceClickListener(pref2);
		} else {
			deletecourses
					.setSummary("You have no courses saved in the Student Notebook");
		}

		dialogBasedPrefCat.addPreference(deletecourses);
		//put phone on silent
		CheckBoxPreference putphoneonSilent = new CheckBoxPreference(this);
		putphoneonSilent.setKey("putphoneonSilent");
		putphoneonSilent.setTitle("Silent Phone");
		putphoneonSilent.setSummary("Puts the phone on silent when entering class");
	
		putphoneonSilent.setOnPreferenceChangeListener(putonSilentListener);
		
		dialogBasedPrefCat.addPreference(putphoneonSilent);
		
		return root;
		
		

	}

}
/**
 AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
		manager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
 * */
 